package com.kedacom.ctsp.authz.security;

import com.kedacom.ctsp.authz.security.aspect.AuthzPermissionAutoEvaluator;
import com.kedacom.ctsp.authz.security.aspect.MethodInvocationAdapter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;


/**
 * 自定义AuhResource的数据行级权限
 *
 * @author xuwei
 * @create 2017-11-29 15:31
 **/
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@EnableConfigurationProperties(AuthzSecurityProperties.class)
public class CustomGlobalMethodSecurityConfiguration extends GlobalMethodSecurityConfiguration {

    @Autowired
    private AuthzSecurityProperties securityProperties;

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new AuthzPermissionAutoEvaluator());
        expressionHandler.setDefaultRolePrefix(securityProperties.getDefaultRolePrefix());
        return expressionHandler;
    }

    /**
     * 前置通知
     */
    @Around("execution(* @annotation(com.kedacom.ctsp.authz.Authorize))")
    public void aroundAuthorize(ProceedingJoinPoint joinPoint) throws Throwable {
        super.methodSecurityInterceptor().invoke(new MethodInvocationAdapter(joinPoint));
    }

}
